package com.example.dw.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.dw.dto.CertificateQueryDTO;
import com.example.dw.dto.NewsQueryDTO;
import com.example.dw.entity.*;
import com.example.dw.mapper.*;
import com.example.dw.service.HomeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页服务实现类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private HomeRundMapper homeRundMapper;

    @Autowired
    private NotifyMapper notifyMapper;

    @Autowired
    private CertificateMapper certificateMapper;


    @Autowired
    private ActivitySessionMapper activitySessionMapper;

    @Autowired
    private SessionPriceMapper sessionPriceMapper;

    @Autowired
    private BulletinMapper bulletinMapper;

    @Override
    public List<Course> getCourseByHot(Integer limit) {
        limit = limit != null && limit > 0 ? limit : 10;
        return courseMapper.getCourseByHot(limit);
    }

    @Override
    public List<Course> getCourseByGood(Integer limit) {
        limit = limit != null && limit > 0 ? limit : 10;
        return courseMapper.getCourseByGood(limit);
    }

    @Override
    public List<Activity> getActiveByNew(Integer limit) {
        limit = limit != null && limit > 0 ? limit : 10;
        List<Activity> active = activityMapper.getActiveByNew(limit);
        // 遍历active，根据activityid获取所有场次，再遍历所有场次id获取价格
        for (Activity activity : active) {
            List<ActivitySession> activitySessions = activitySessionMapper.getActivitySessionByActivityId(activity.getActivityid());
            // 如果activitySessions为null，初始化为空列表
            if (activitySessions == null) {
                activitySessions = new java.util.ArrayList<>();
            } else {
                for (ActivitySession activitySession : activitySessions) {
                    List<SessionPrice> sessionPrices = sessionPriceMapper.getSessionPriceBySessionId(activitySession.getSessionid());
                    activitySession.setActivityPrices(sessionPrices);
                }
                // 过滤掉价格列表为空的场次
                activitySessions.removeIf(activitySession -> 
                    activitySession.getActivityPrices() == null || activitySession.getActivityPrices().isEmpty()
                );
            }
            // 重要：将场次数据设置到activity对象中
            activity.setActivitySessions(activitySessions);
        }
        // 遍历active.activitySessions.activityPrices，如果所有场次的价格都为空，则移除该activity
        active.removeIf(activity -> {
            List<ActivitySession> sessions = activity.getActivitySessions();
            if (sessions == null || sessions.isEmpty()) {
                return true; // 移除没有场次的活动
            }
            // 检查是否所有场次都没有价格
            return sessions.stream().allMatch(activitySession -> 
                activitySession.getActivityPrices() == null || activitySession.getActivityPrices().isEmpty()
            );
        });
       
        return active;
    }

    @Override
    public List<News> getNewsByNew(Integer limit) {
        limit = limit != null && limit > 0 ? limit : 10;
        return newsMapper.getNewsByNew(limit);
    }

    @Override
    public Map<String, Object> getCourseByHotWeb(Integer page, Integer size) {
        page = page != null && page > 0 ? page : 1;
        size = size != null && size > 0 ? size : 10;
        
        Integer offset = (page - 1) * size;
        List<Course> courses = courseMapper.getCourseByHotWeb(offset, size);
        Integer total = courseMapper.getCourseHotCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", courses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getCourseByGoodWeb(Integer page, Integer size) {
        page = page != null && page > 0 ? page : 1;
        size = size != null && size > 0 ? size : 10;
        
        Integer offset = (page - 1) * size;
        List<Course> courses = courseMapper.getCourseByGoodWeb(offset, size);
        Integer total = courseMapper.getCourseGoodCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", courses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getActiveByNewWeb(Integer page, Integer size) {
        page = page != null && page > 0 ? page : 1;
        size = size != null && size > 0 ? size : 10;
        
        Integer offset = (page - 1) * size;
        List<Activity> activities = activityMapper.getActiveByNewWeb(offset, size);
        Integer total = activityMapper.getActiveCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", activities);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getNewsByNewWeb(Integer page, Integer size) {
        page = page != null && page > 0 ? page : 1;
        size = size != null && size > 0 ? size : 10;
        
        Integer offset = (page - 1) * size;
        List<News> newsList = newsMapper.getNewsByNewWeb(offset, size);
        Integer total = newsMapper.getNewsCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public News getNewsById(Integer newsid) {
        if (newsid == null) {
            throw new RuntimeException("新闻ID不能为空");
        }
        return newsMapper.getNewsById(newsid);
    }

    @Override
    public Map<String, Object> getAllNewsUni(NewsQueryDTO queryDTO) {
        Integer page = queryDTO.getPage() != null && queryDTO.getPage() > 0 ? queryDTO.getPage() : 1;
        Integer size = queryDTO.getSize() != null && queryDTO.getSize() > 0 ? queryDTO.getSize() : 10;
        Integer offset = (page - 1) * size;

        List<News> newsList;
        Integer total;

        if (StrUtil.isNotBlank(queryDTO.getKeyword())) {
            // 根据关键字搜索
            newsList = newsMapper.searchNewsByKeyword(queryDTO.getKeyword(), offset, size);
            total = newsMapper.getNewsCountByKeyword(queryDTO.getKeyword());
        } else {
            // 获取所有新闻
            newsList = newsMapper.getAllNewsPage(offset, size);
            total = newsMapper.getNewsCount();
        }


        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public Map<String, Object> getAllNewsPage(Integer page, Integer size) {
        page = page != null && page > 0 ? page : 1;
        size = size != null && size > 0 ? size : 10;
        
        Integer offset = (page - 1) * size;
        List<News> newsList = newsMapper.getAllNewsPage(offset, size);
        Integer total = newsMapper.getNewsCount();

        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);

        return result;
    }

    @Override
    public List<HomeRund> getRunningText() {
        return homeRundMapper.getRunningText();
    }

    @Override
    public List<Notify> getNotifyList() {
        return notifyMapper.getNotifyList();
    }

    @Override
    public String getMirror() {
        // TODO: 实现镜像文章功能
        // 这里应该返回镜像文章的内容或者URL
        return "镜像文章功能待实现";
    }

    @Override
    public String getMirrorImg() {
        // TODO: 实现镜像图片功能
        // 这里应该返回镜像图片的URL
        return "镜像图片功能待实现";
    }

    @Override
    public List<Certificate> searchCertificate(CertificateQueryDTO queryDTO) {
        return certificateMapper.searchCertificate(
                queryDTO.getName(),
                queryDTO.getCertificateidSfz(),
                queryDTO.getPhone(),
                queryDTO.getCertificateidBh()
        );
    }

    @Override
    public List<Bulletin> getBulletinList() {
        return bulletinMapper.getBulletinList();
    }
} 